package com.ftg.learn.chapter09.collection;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 循环map
 *
 * @author lijiaxin
 * @version 1.0
 * @date 2023/8/17 13:23
 */

public class MapShowAll {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<>(2);

        map.put("name", "li");
        map.put("age", "16岁");

        System.out.println("第一种遍历：通过key获取，然后再用key取value");

        //获取所有的key
        Set<String> keys = map.keySet();
        keys.forEach(System.out::println);
        keys.forEach((x)->{
            String s =map.get(x);
            System.out.printf("map里面的key为%s,value为%s\n", x, s);
        });

        //迭代器
        Iterator<String> it= keys.iterator();
        while (it.hasNext()){
            String next = it.next();
            System.out.println(next);
        }

        System.out.println("第二种：通过values，只能获取值");
        Collection<String> values = map.values();
        values.forEach(System.out::println);

        System.out.println("第三种：entrySet 强烈");
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry:entries) {
            System.out.println("key==>"+entry.getKey());
            System.out.println("value==>"+entry.getValue());
        }

        System.out.println("第四种：foreach");
        //原子性
        AtomicReference<String> lastkey = new AtomicReference<>();
        map.forEach((k,v)-> {
            lastkey.set(k);
            System.out.printf("k=%s,v=%s\n",k,v);
        });
        System.out.println(lastkey.get());


//        jdk1.6 ---> 数组  (丢数据 --- hash冲突)
//        jdk1.7 ---> 数组+链表 (解决 hash冲突)
//        jdk1.8 ---> 数组+链表 + 红黑树 (链表过长查找速度过慢)


        System.out.println(tableSizeFor(5));  //比5大的最小的二的次幂 8

    }

    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : n + 1;
    }
}
